import { ab_to_str, str_to_ab } from "../../utils/util";

var app = getApp();     
var nfc_timerID = 0;    
var udp_timerID = 0;    
var udp = null;         
const fs = wx.getFileSystemManager();
Page({
  set_wifi_ssid(e)      //wifi账号设置函数
  {
    app.my_data.wifi_ssid = e.detail.value;
    console.log("wifi_ssid:"+e.detail.value);
  },
  set_wifi_passwd(e)    //WiFi密码设置函数
  {
    app.my_data.wifi_passwd = e.detail.value;
    console.log("wifi_passwd:"+e.detail.value);
  },
  set_client_ip(e)      //本机ip设置函数
  {
    app.my_data.client_ip = e.detail.value;
    console.log("client_ip:"+e.detail.value);
  },
  jump_to_smartCar()    //智能小车跳转界面
  {
    console.log('跳转到智能小车界面');
    wx.showActionSheet({
      itemList: ['手动驾驶','自动巡检','自动驾驶'],
      alertText: 'alertText',
      itemColor: 'itemColor',
      success: (result) => {
        console.log(result.tapIndex);
        //手动驾驶
        if (result.tapIndex == 0) { 
          console.log('手动驾驶模式');
          wx.navigateTo({
          url: '/pages/car_ctl/car_ctl',
          })
        }
        else if (result.tapIndex == 1) {
          console.log('自动巡检模式');
          wx.navigateTo({
            url: '/pages/car_tarck/car_tarck',
          })
        }
        else if (result.tapIndex == 2) {
          console.log('自动驾驶模式');
          wx.navigateTo({
            url: '/pages/car_driverless/car_driverless',
          })
        }
      },
      fail: (res) => {
        console.log(res.errMsg);
      },
    })
  },
  /**
   * 页面的初始数据
   */
  data: {
    
  },
  // 启动NFC搜寻函数
  startDiscovery() {
    // this.addlog({
    //   time: util.formatTime(new Date()),
    //   text: "请将设备放入NFC识别区",
    // });
    this.NFCAdapter.startDiscovery({
      success: (res) => {
        console.log('startDiscovery success');
        console.log(res);
      },
      fail: (error) => {
        console.log('startDiscovery error');
        console.log(error);
      },
    });
  },
  // NFC连接设备函数
  NFCconnect() {
    this.NFCTab.connect({
      success: (res) => {
        wx.showToast({
          title: "已连接设备",
          icon: "success",
        });
        // 执行写入信息
        this.write_to_nfc();
        //clearInterval(timerID);
      },
      fail: (error) => {
        wx.showToast({
          title: "请靠近设备",
          icon: "error",
        });
      },
      complete: (res) => {
        console.log(res);
      },
    });
  },
  //向NFC写入文本内容
  write_to_nfc(){
    // var payload = `{"device_id":"smart_car","parameter":{"wifi_ssid":"${app.my_data.wifi_ssid}","wifi_passwd":"${app.my_data.wifi_passwd}","client_ip":"${app.my_data.client_id}"}}`;
    // const records = [
    //   {
    //     id: str_to_ab(new Date().getTime().toString()),
    //     type: str_to_ab("text"),
    //     payload: str_to_ab(payload),
    //     tnf: 0x02,
    //   },
    // ];
    // this.writeNdefMessage(records);
    var record = `""{"device_id":"smart_car","parameter":{"wifi_ssid":"${app.my_data.wifi_ssid}","wifi_passwd":"${app.my_data.wifi_passwd}","client_ip":"${app.my_data.client_ip}"}}`;
    this.writeNdefMessage(record);
  },
  // 执行写入
   writeNdefMessage(records) {
    wx.showToast({
      title: "正在执行写入",
      icon: "success",
    });
    this.NFCTab.writeNdefMessage({
      uris: [records],
      //texts: [{}],
      //records: records,
      success: (res) => {
        wx.showToast({
          title: "写入数据成功",
          icon: "success",
        });
        udp_timerID = setTimeout(()=>{
          wx.showToast({
            title: "网络配置失败",
            icon: "error",
          });
        },10000)   //设置五秒延时等待服务器回传 'ok';
        
      },
      fail: (error) => {
        console.log(error);
        wx.showToast({
          title: "写入数据失败",
          icon: "error",
        });
      },
      complete: () => {
        this.setData({
          disabled: false,
        });
        // 断开连接
        this.NFCTab.close();
        // 关闭定时器
        clearInterval(nfc_timerID);
      },
    });
  },
  nfc_networking(){   //nfc配网
    console.log('尝试NFC配置');
    var that = this;
    nfc_timerID = setInterval(()=>{
      wx.showToast({
        title: "请靠近设备",
        icon: "loading",
      });
      // 搜寻设备
      that.startDiscovery();
      // 连接设备
      that.NFCconnect();
    }, 1500)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    // 初始化NFC
    that.NFCAdapter = wx.getNFCAdapter();
    // 获取NDEF对象
    that.NFCTab = that.NFCAdapter.getNdef();

    // 打开本地备份服务器ip文件
    fs.open({
      filePath: `${wx.env.USER_DATA_PATH}/ServerIP.txt`,
      flag: 'a+',
      success(res) {
        console.log(res.fd)
      }
    })
    fs.readFile({         //读取服务器ip
      filePath: `${wx.env.USER_DATA_PATH}/ServerIP.txt`,
      encoding: 'utf8',
      position: 0,
      success(res) {
        console.log(res.data)
        app.my_data.server_ip = res.data;
        //this.data.server_ip = res.data;
      },
      fail(res) {
        console.error(res)
      }
    })
    
    //初始化udp客户端
    udp = app.my_data.udp;
    let _port  = udp.bind(app.my_data.client_port)
    console.log('client port:'+ _port);
    udp.onError((e) => {
      console.log(e);
    });
    udp.onMessage((res)=>{  //对接服务器，获取服务器信息
      console.log(res.remoteInfo);
      //若记录的ip与服务器ip不符，则修改记录的ip信息
      if(app.my_data.server_ip != res.remoteInfo.address) 
      {
        app.my_data.server_ip = res.remoteInfo.address;
        fs.writeFile({  //把新ip保存到本地文件
          filePath:`${wx.env.USER_DATA_PATH}/ServerIP.txt`,
          data: app.my_data.server_ip,
          encoding : 'utf8',
          success(res) {
            console.log(res)
          },
          fail(res) {
            console.error(res)
          }
        })
      }
      //对收到的message进行类型转换，ArrayBuffer转string
      var buffer = res.message;
      var dataview = new DataView(buffer);
      var ints = new Uint8Array(buffer.byteLength);
      var str = '';
      for (var i = 0; i < ints.length; i++) {
        str += String.fromCharCode(dataview.getUint8(i));
      }
      console.log("message=> "+str);
      if (str == 'ok') {    //服务器'ok'则网络配置成功
        clearTimeout(udp_timerID);
        wx.showToast({
          title: "网络配置成功",
          icon: "success",
        });
        // 界面加载就先直接尝试连接服务器
        udp.send({
          address: app.my_data.server_ip,
          port: app.my_data.server_port,
          message: "ok"
        })
        udp.offMessage();
      }
    })
  },
  connect_to_wifi() //手动连接wifi函数
  {
    wx.startWifi();
    wx.onWifiConnected((result) => {
      console.log(result);
    })
    wx.connectWifi({
      SSID: app.my_data.wifi_ssid,
      password: app.my_data.wifi_passwd,
      success : (res)=>{
        wx.showToast({
          title: "wifi连接成功",
          icon: "success",
        });
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})